import json
from fastapi import Depends, APIRouter
from pydantic import BaseModel

from api import sql_polars, sqlpyodbc
from util.JWT import get_current_user

acl_adduser = APIRouter()

# 获取用户列表
@acl_adduser.get("/getuser")
async def getuser(id: dict = Depends(get_current_user)):
    sql = f"SELECT UserNumber FROM UserManagement"
    df = sql_polars.query(sql)
    if df.height < 1:
        return {
            "code": 204,
            "status": "no",
            "msg": "没有内容",
            "data": []
        }
    df = df.to_dicts()
    json_string = json.dumps(df, ensure_ascii=False)
    return {
        "code": 200,
        "status": "ok",
        "msg": "success",
        "data": json_string
    }

# 添加用户

class adduserType(BaseModel):
    UserNumber: str
    UserName: str


@acl_adduser.post("/adduser")
async def adduser(data: adduserType, id: dict = Depends(get_current_user)):
    sql = f"INSERT INTO UserManagement(UserNumber,UserPwd,UserName,Whse,Dept,Bud) VALUES('{data.UserNumber}','123456','{data.UserName}','蓝思','安吉','无')"
    try:
        if sqlpyodbc.execute(sql) > 0:
            return {"code": 200, "status": "ok", "msg": "success"}
        return {"code": 400, "status": "no", "msg": "error"}
    except:
        return {"code": 400, "status": "no", "msg": "error"}


 # 修改密码
class updatepwdType(BaseModel):
    UserNumber: str
    newpwd: str
@acl_adduser.post("/updatepwd")
async def updatepwd(data: updatepwdType, id: dict = Depends(get_current_user)):
    sql = f"UPDATE UserManagement SET UserPwd='{data.newpwd}' WHERE UserNumber='{data.UserNumber}'"
    try:
        if sqlpyodbc.execute(sql) > 0:
            return {"code": 200, "status": "ok", "msg": "success"}
        return {"code": 400, "status": "no", "msg": "error"}
    except:
        return {"code": 400, "status": "no", "msg": "error"}



